import db from '@adonisjs/lucid/services/db'
import StockOrderModel from '#models/stock_order'
import StockOutDetailModel from '#models/stock_out_detail'
import { CreateStockOutValidator } from '#validators/stock'
import HttpException from '#exceptions/http_exception'

export default class StockOutService {
  static async create(billType: string, data: CreateStockOutValidator) {
    const trx = await db.transaction()
    try {
      data.billType = billType
      data.stockType = 'OUT'
      const { stockOutDetail, ...stockOrder } = data
      const stockInInfo = await StockOrderModel.create(stockOrder)
      await StockOutDetailModel.generateCreate(stockInInfo, stockOutDetail)
      await trx.commit()
    } catch (error) {
      await trx.rollback()
      throw new HttpException(error, {
        code: error.code,
        status: 500,
      })
    }
  }

  static async update(orderId: number, data: CreateStockOutValidator) {
    const stockInInfo = await StockOrderModel.findOrFail(orderId)

    const trx = await db.transaction()
    try {
      stockInInfo.merge(data)

      await Promise.all([
        stockInInfo.save(),
        StockOutDetailModel.query().where('fkStockOrderId', orderId).delete(),
        StockOutDetailModel.generateCreate(stockInInfo, data.stockOutDetail),
        trx.commit(),
      ])
    } catch (error) {
      await trx.rollback()
      throw new HttpException(error, {
        code: error.code,
        status: 500,
      })
    }
  }

  static async delete(id: string) {
    const stockOrder = await StockOrderModel.findOrFail(id)
    const trx = await db.transaction()
    try {
      await Promise.all([
        StockOutDetailModel.query().where('fkStockOrderId', id).delete(),
        stockOrder.delete(),
        trx.commit(),
      ])
    } catch (error) {
      await trx.rollback()
      throw new HttpException(error, {
        code: error.code,
        status: 500,
      })
    }
  }
}
